# coding: utf-8
from django.contrib.auth.models import User,Group
from rest_framework import viewsets,permissions
from rest_framework import status
from rest_framework.decorators import api_view,permission_classes
from rest_framework.response import Response
# from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope
from jd_asset.models import AssetInfo
from .serializers import AssetInfoSerializer,UserSerializer,GroupSerializer

# Create your views here.
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # permission_classes = (permissions.IsAuthenticated,)

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    # permission_classes = (permissions.IsAuthenticated,)

class AssetInfoViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = AssetInfoSerializer
    # permission_classes = (permissions.IsAuthenticated,)

@api_view(['GET','POST'])
@permission_classes((permissions.IsAuthenticatedOrReadOnly,))
def assets_list(request):
    """
    GET 获取已有的资产列表
    POST 建立新的资产
    """
    if request.method == 'GET':
        # 测试 只返回前十条
        assets = AssetInfo.objects.all()[:10]
        serializer = AssetInfoSerializer(assets,many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = AssetInfoSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
